package com.zwz.mall.managers;

import android.content.Context;

import com.zwz.mall.config.Config;
import com.zwz.mall.models.User;
import com.zwz.mall.utils.SPUtils;
import com.zwz.mall.utils.SerialUtils;

import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;

/**
 * Created by Administrator on 2019/6/3 0003.
 * 单例模式
 */

public class UserManager {

    public static User mUser;
    private PublishSubject<User> mMallManagerStatusObserver = null;//用户信息
    private PublishSubject<Boolean> mLoginMallManagerStatusObserver = null;//登录状态

    private static UserManager mUserManager;
    private static volatile UserManager sInst = null;  // <<< 这里添加了 volatile

    public static UserManager getInstance() {
        UserManager inst = sInst;  // <<< 在这里创建临时变量
        if (inst == null) {
            synchronized (UserManager.class) {
                inst = sInst;
                if (inst == null) {
                    inst = new UserManager();
                    sInst = inst;
                }
            }
        }
        return inst;  // <<< 注意这里返回的是临时变量
    }

    public User getUser(Context context) {
        if (mUser == null) {
            //取用户信息
            String userTokenStr = SPUtils.getSharedStringData(context, Config.USER_TOKEN);
            SerialUtils<User> userSerialUtils1 = new SerialUtils<>();//new 一个工具类
            try {
                mUser = userSerialUtils1.deSerialization(userTokenStr);//反序列化对象
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return mUser;
    }

    public User getUser() {

        return mUser;
    }

    public void setUser(User mUser) {
        UserManager.mUser = mUser;
    }

    public UserManager() {
        mLoginMallManagerStatusObserver = PublishSubject.create();
        mMallManagerStatusObserver = PublishSubject.create();
    }

    //发送事件
    public void onStatuesChange(User user) {
        mMallManagerStatusObserver.onNext(user);
    }

    /**
     * 状态变化观察者
     * 接收事件
     *
     * @return
     */
    public Observable<Boolean> asLogoinManagerStatusObservable() {
        return mLoginMallManagerStatusObserver;
    }

    //发送事件
    public void onLoginStatuesChange(Boolean b) {
        mLoginMallManagerStatusObserver.onNext(b);
    }

    /**
     * 状态变化观察者
     * 接收事件
     *
     * @return
     */
    public Observable<User> asManagerStatusObservable() {
        return mMallManagerStatusObserver;
    }
    //发送事件
    public void onLoginStatuesChange(User user) {
        mMallManagerStatusObserver.onNext(user);
    }

}
